{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "避免全局变量"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 不推荐写法。代码耗时：26.8秒\n",
    "import math\n",
    " \n",
    "size = 10000\n",
    "for x in range(size):\n",
    "    for y in range(size):\n",
    "        z = math.sqrt(x) + math.sqrt(y)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 推荐写法。代码耗时：20.6秒\n",
    "import math\n",
    " \n",
    "def main():  # 定义到函数中，以减少全部变量使用\n",
    "    size = 10000\n",
    "    for x in range(size):\n",
    "        for y in range(size):\n",
    "            z = math.sqrt(x) + math.sqrt(y)\n",
    " \n",
    "main()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "避免.\n",
    "每次使用.（属性访问操作符时）会触发特定的方法，如__getattribute__()和__getattr__()，这些方法会进行字典操作，因此会带来额外的时间开销。通过from import语句，可以消除属性访问。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 不推荐写法。代码耗时：14.5秒\n",
    "import math\n",
    " \n",
    "def computeSqrt(size: int):\n",
    "    result = []\n",
    "    for i in range(size):\n",
    "        result.append(math.sqrt(i))\n",
    "    return result\n",
    " \n",
    "def main():\n",
    "    size = 10000\n",
    "    for _ in range(size):\n",
    "        result = computeSqrt(size)\n",
    " \n",
    "main()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 第一次优化写法。代码耗时：10.9秒\n",
    "from math import sqrt\n",
    " \n",
    "def computeSqrt(size: int):\n",
    "    result = []\n",
    "    for i in range(size):\n",
    "        result.append(sqrt(i))  # 避免math.sqrt的使用\n",
    "    return result\n",
    " \n",
    "def main():\n",
    "    size = 10000\n",
    "    for _ in range(size):\n",
    "        result = computeSqrt(size)\n",
    " \n",
    "main()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "字符串拼接用join而不是+\n",
    "当使用a + b拼接字符串时，由于 Python 中字符串是不可变对象，其会申请一块内存空间，将a和b分别复制到该新申请的内存空间中。因此，如果要拼接n个字符串，会产生 n-1个中间结果，每产生一个中间结果都需要申请和复制一次内存，严重影响运行效率。而使用join()拼接字符串时，会首先计算出需要申请的总的内存空间，然后一次性地申请所需内存，并将每个字符串元素复制到该内存中去。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 不推荐写法，代码耗时：2.6秒\n",
    "import string\n",
    "from typing import List\n",
    " \n",
    "def concatString(string_list: List[str]) -> str:\n",
    "    result = ''\n",
    "    for str_i in string_list:\n",
    "        result += str_i\n",
    "    return result\n",
    " \n",
    "def main():\n",
    "    string_list = list(string.ascii_letters * 100)\n",
    "    for _ in range(10000):\n",
    "        result = concatString(string_list)\n",
    " \n",
    "main()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 推荐写法，代码耗时：0.3秒\n",
    "import string\n",
    "from typing import List\n",
    " \n",
    "def concatString(string_list: List[str]) -> str:\n",
    "    return ''.join(string_list)  # 使用 join 而不是 +\n",
    " \n",
    "def main():\n",
    "    string_list = list(string.ascii_letters * 100)\n",
    "    for _ in range(10000):\n",
    "        result = concatString(string_list)\n",
    " \n",
    "main()"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "jupter-env-10",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.16"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
